import React, {
    Fragment,
    PureComponent
} from 'react';

import Picker,{
    Options
} from 'react-native-image-crop-picker';

import {
    Modal,
} from './../../components';

interface Props {
    children?:any,
    onChange:Function,
    cropping:boolean,
    mediaType:'photo'|'video',
    useFrontCamera:boolean
}

interface State {
    show:boolean
}

import Menu from './menu';

class File extends PureComponent<Props,State> {

    state = {
        show:false
    }

    static defaultProps = {
        cropping:true,
        mediaType:'photo',
        onChange:() => null,
        useFrontCamera:true
    }

    _onPress = () => {
        this.setState({
            show:true
        })
    }

    _onClose = () => {
        this.setState({
            show:false
        })
    }

    get options() {
        const {
            cropping,
            mediaType,
            useFrontCamera
        } = this.props;

        return  {
            cropping,
            mediaType,
            useFrontCamera,
            compressImageQuality:.5
        } as Options;
    }

    _onTakeCamera = async () => {
        const {
            onChange
        } = this.props;

        try {
            onChange(
                await Picker.openCamera(this.options)
            )
        }
        catch (e) {
            console.log(e)
        }

        this._onClose()
    }

    _onChooseLibrary = async () => {
        const {
            onChange
        } = this.props;

        try {
            onChange(
                await Picker.openPicker(
                    this.options
                )
            )
        }
        catch (e) {
            console.log(e)
        }

        this._onClose()
    }

    render() {
        const {
            children
        } = this.props;

        const {
            show
        } = this.state;

        return (
            <Fragment>
                {React.cloneElement(children, {
                    onPress: this._onPress
                })}
                <Modal
                    fixed={false}
                    show={show}
                    direction="bottom"
                    onClose={this._onClose}
                >
                    <Menu
                        onCancel={this._onClose}
                        onTakeCamera={this._onTakeCamera}
                        onChooseLibrary={this._onChooseLibrary}
                    />
                </Modal>
            </Fragment>
        )
    }
}

export default File;